<?php

/**
 * Created by PhpStorm.
 * User: lili
 * Date: 19-1-30
 * Time: 上午12:52
 */

$dbms='mysql';     //数据库类型
$host='localhost'; //数据库主机名
$dbName='redis';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='123456';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";

try {
    $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
    echo "连接成功<br/>";
    $dbh->beginTransaction();


    $dbh->query(' lock table goods write ');//这个是myisam的锁，可以满足要求

    $res = $dbh->query(' SELECT * from goods where id = 1 ')->fetchAll();
//    var_dump($res);
    $leftnum = $res[0]['num'];
    if($leftnum<=0){
        exit();
    }

    $dbh->query('update goods set num=num-1 where id = 1') ;
    /*你还可以进行一次搜索操作 */
    foreach ($dbh->query('SELECT * from goods') as $row) {
        var_dump($row['num']); //你可以用 echo($GLOBAL); 来看到这些值
    }

    $dbh->commit();
    $dbh->query(' unlock tables ');

    $dbh = null;
} catch (PDOException $e) {
    $dbh->rollBack();
    die ("Error!: " . $e->getMessage() . "<br/>");
}

